package com.softcits.sb01.servlet;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/download")
public class Download extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String fileName = req.getParameter("fileName");

		System.out.println("要下载的文件名: " + fileName);

		String rootPath = req.getServletContext().getRealPath("/");

		System.out.println("项目静态资源的根目录: " + rootPath);

		String fullFilePath = rootPath + fileName;

		System.out.println("要下载的文件是: " + fullFilePath);
		
		 //得到读取本地文件的输入流
		FileInputStream fis = new FileInputStream(fullFilePath);
		//得到文件向网络传输的输出流
		ServletOutputStream out = resp.getOutputStream();
		
		resp.setCharacterEncoding("utf-8");
	    resp.setHeader("Content-Disposition", "attachment; filename="+fileName);
		
		int data = 0;
		byte[] unit = new byte[1024];
		while ((data = fis.read(unit)) != -1) {
			out.write(unit, 0, data);
		}
		fis.close();
		out.close();

		/*
		 * String path =
		 * getServletContext().getRealPath("C:/study/git/ws/sb01/src/main/webapp/"+
		 * fileName);
		 * resp.setContentType(this.getServletContext().getMimeType(fileName));
		 * FileInputStream fis = new FileInputStream(path); OutputStream fos =
		 * resp.getOutputStream(); int data =0; byte[] unit = new byte[1024];
		 * while((data = fis.read())!= -1) { fos.write(unit, 0, data); } fis.close();
		 * fos.close();
		 */
	}

}
